<template>
  <div>
    <a-card :bordered="false" style="margin-bottom: 10px">
      <!-- 条件搜索 -->
      <div class="table-page-search-wrapper">
        <a-form :labelCol="labelCol" :wrapperCol="wrapperCol" ref="queryForm">
          <a-row :gutter="32">
            <a-col :span="6">
              <a-form-item label="新闻标题">
                <a-input
                  v-model="queryParam.title"
                  placeholder="请输入新闻标题"
                  allow-clear
                  @keyup.enter.native="handleQuery"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="所属企业">
                <a-tree-select
                  v-model="queryParam.deptId"
                  placeholder="请选择所属企业"
                  :tree-data="deptOptions"
                  tree-default-expand-all
                  :replaceFields="{
                    children: 'children',
                    title: 'title',
                    key: 'id',
                    value: 'id',
                  }"
                  allow-clear
                >
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="创建时间">
                <a-range-picker
                  v-model="dateRange"
                  style="width: 100%"
                  valueFormat="YYYY-MM-DD"
                  format="YYYY-MM-DD"
                  allow-clear
                >
                </a-range-picker>
              </a-form-item>
            </a-col>
            <a-col>
              <span
                class="table-page-search-submitButtons"
                style="float: right"
              >
                <a-button type="primary" @click="handleQuery"
                  ><a-icon type="search" />查询</a-button
                >
                <a-button style="margin-left: 8px" @click="resetQuery"
                  ><a-icon type="redo" />重置</a-button
                >
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
    </a-card>
    <a-card :bordered="false" class="table-card">
      <!-- 增加 -->
      <biz-news-add-form
        v-if="showAddModal"
        ref="bizNewsAddForm"
        @ok="getList"
        @close="showAddModal = false"
      />
      <!-- 编辑 -->
      <biz-news-edit-form
        v-if="showEditModal"
        ref="bizNewsEditForm"
        @ok="getList"
        @close="showEditModal = false"
      />
      <advance-table
        title="新闻信息"
        :pagination="{
          current: queryParam.pageNum,
          pageSize: queryParam.pageSize,
          total: total,
          showSizeChanger: true,
          showLessItems: true,
          showQuickJumper: true,
          showTotal: (total, range) =>
            `第 ${range[0]}-${range[1]} 条，总计 ${total} 条`,
          onChange: changeSize,
          onShowSizeChange: onShowSizeChange,
        }"
        tableKey="base-bizNews-index-table"
        rowKey="id"
        size="middle"
        @refresh="getList"
        :columns="columns"
        :data-source="bizNewsList"
        :loading="loading"
        :format-conditions="true"
        :row-selection="{
          selectedRowKeys: selectedRowKeys,
          onChange: onSelectChange,
        }"
      >
        <div class="table-operations" slot="button">
          <a-button
            type="primary"
            @click="handleAdd"
            v-hasPermi="['biz:bizNews:add']"
          >
            <a-icon type="plus" />新增
          </a-button>

          <a-button
            type=""
            @click="onDownLoad"
            v-hasPermi="['biz:bizNews:export']"
          >
            <a-icon type="download" />下载新闻
          </a-button>
          <a-button
            type="danger"
            v-if="!multiple"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['biz:bizNews:remove']"
          >
            <a-icon type="delete" />删除
          </a-button>
        </div>

        <span slot="operation" slot-scope="{ text, record }">
          <a @click="handleUpdate(record)" v-hasPermi="['biz:bizNews:edit']">
            修改
          </a>
          <a-divider type="vertical" v-hasPermi="['biz:bizNews:remove']" />
          <a @click="handleDelete(record)" v-hasPermi="['biz:bizNews:remove']">
            删除
          </a>
        </span>
        <span slot="rowindex" slot-scope="{ index }">
          {{ index + 1 }}
        </span>
        <span slot="fileName" slot-scope="{ record }">
          <a target="_blank" :href="record.fileUrl">{{ record.fileName }}</a>
        </span>
      </advance-table>
    </a-card>
    <a-modal
      :visible="isDownloading"
      title="文件下载"
      :footer="null"
      :closable="false"
      :maskClosable="false"
      width="400px"
    >
      <div class="progress-container">
        <a-typography-text>{{ statusText }}</a-typography-text>
        <a-progress
          :percent="progress"
          status="active"
          style="margin: 16px 0"
        />
        <a-typography-text type="secondary">
          正在处理文件，请稍候...
        </a-typography-text>
      </div>
    </a-modal>
  </div>
</template>
<script>
import { listBizNews, delBizNews, exportBizNews } from "@/api/biz/bizNews";
import { listDeptTree } from "@/api/system/dept";
import AdvanceTable from "@/components/pt/table/AdvanceTable";
import BizNewsAddForm from "@/views/biz/news/modules/BizNewsAddForm";
import BizNewsEditForm from "@/views/biz/news/modules/BizNewsEditForm";
import JSZip from "jszip";
export default {
  name: "BizNews",
  components: {
    AdvanceTable,
    BizNewsAddForm,
    BizNewsEditForm,
  },
  data() {
    return {
      showAddModal: false,
      showEditModal: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中的主键集合
      selectedRowKeys: [],
      // 选中的数据集合
      selectedRows: [],
      // 高级搜索 展开/关闭
      advanced: false,
      // 非单个禁用
      single: true,
      statusText: "准备中...",
      progress: 0,
      isDownloading: false,
      selectedFiles: [],
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // label的百分比
      labelCol: { span: 6 },
      // 内容区域的百分比
      wrapperCol: { span: 18 },
      // 新闻管理表格数据
      bizNewsList: [],
      deptOptions: [],
      dateRange: [],
      // 查询参数
      queryParam: {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        fileName: undefined,

        fileUrl: undefined,

        userName: undefined,

        deptName: undefined,

        title: undefined,
        params: {},
      },
      columns: [
        {
          title: "序号",
          dataIndex: "rowindex",
          ellipsis: true,
          align: "center",
          width: "5%",
          scopedSlots: { customRender: "rowindex" },
        },
        {
          title: "部门名称",
          dataIndex: "deptName",
          ellipsis: true,
          align: "center",
          width: "15%",
        },
        {
          title: "新闻标题",
          dataIndex: "title",
          ellipsis: true,
          align: "center",
          width: "20%",
        },
        {
          title: "创建人员",
          dataIndex: "userName",
          ellipsis: true,
          align: "center",
          width: "10%",
        },
        {
          title: "创建时间",
          dataIndex: "createTime",
          ellipsis: true,
          align: "center",
          width: "12%",
        },
        {
          title: "修改人员",
          dataIndex: "updateBy",
          ellipsis: true,
          align: "center",
          width: "10%",
        },
        {
          title: "修改时间",
          dataIndex: "updateTime",
          ellipsis: true,
          align: "center",
          width: "12%",
        },

        {
          title: "新闻附件",
          dataIndex: "fileName",
          ellipsis: true,
          align: "left",
          width: "25%",
          scopedSlots: { customRender: "fileName" },
        },
        {
          title: "操作",
          dataIndex: "operation",
          align: "center",
          width: "10%",
          scopedSlots: { customRender: "operation" },
        },
      ],
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    getTreeselect() {
      listDeptTree("0", 3).then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询新闻管理列表 */
    getList() {
      this.loading = true;
      if (
        this.dateRange !== null &&
        this.dateRange !== "" &&
        this.dateRange.length === 2
      ) {
        this.queryParam.params.beginTime = this.dateRange[0];
        this.queryParam.params.endTime = this.dateRange[1];
      }
      listBizNews(this.queryParam).then((response) => {
        this.bizNewsList = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParam.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParam = {
        pageNum: 1,
        pageSize: 10,
        userId: undefined,

        deptId: undefined,

        fileName: undefined,

        fileUrl: undefined,

        userName: undefined,

        deptName: undefined,

        title: undefined,
      };
      this.handleQuery();
    },
    async onDownLoad() {
      if (this.selectedRows.length > 0) {
        this.isDownloading = true;
        this.statusText = "正在创建ZIP文件...";
        this.progress = 0;

        this.selectedFiles = this.selectedRows.map((item) => {
          return {
            name: item.fileName,
            url: item.fileUrl,
          };
        });

        try {
          const zip = new JSZip();

          // 使用 for...of 循环以便使用 await
          for (let i = 0; i < this.selectedFiles.length; i++) {
            const file = this.selectedFiles[i];
            this.statusText = `添加文件中: ${file.name} (${i + 1}/${
              this.selectedFiles.length
            })`;

            try {
              // 使用 await 获取实际的 blob 内容
              const blob = await this.downloadFileAsBlob(file.url);

              // 将文件添加到ZIP
              zip.file(file.name, blob);

              // 更新进度
              this.progress = ((i + 1) / this.selectedFiles.length) * 100;

              // 添加一点延迟，使进度更明显
              await new Promise((resolve) => setTimeout(resolve, 300));
            } catch (fileError) {
              console.error(`下载文件 ${file.name} 失败:`, fileError);
              // 可以选择跳过失败的文件或终止整个操作
              continue;
            }
          }

          this.statusText = "正在生成ZIP文件...";

          try {
            // 使用 await 获取生成的 ZIP blob
            const zipBlob = await zip.generateAsync(
              {
                type: "blob",
                compression: "DEFLATE", // 添加压缩选项
                compressionOptions: {
                  level: 6, // 压缩级别 1-9
                },
              },
              (metadata) => {
                // 可以在这里添加生成进度回调
                console.log("ZIP生成进度:", metadata.percent);
                this.progress = Number(metadata.percent).toFixed(2);
              }
            );

            // 创建下载链接
            const link = document.createElement("a");
            const blobUrl = URL.createObjectURL(zipBlob);
            link.href = blobUrl;

            const fileName = `新闻文件_${new Date()
              .toISOString()
              .slice(0, 10)}.zip`;
            link.download = fileName;
            link.style.display = "none";

            document.body.appendChild(link);
            link.click();

            // 清理
            setTimeout(() => {
              document.body.removeChild(link);
              URL.revokeObjectURL(blobUrl);
            }, 100);

            this.statusText = "下载完成！";
            this.progress = 100;

            // 2秒后隐藏进度条
            setTimeout(() => {
              this.isDownloading = false;
            }, 2000);
          } catch (generateError) {
            console.error("生成ZIP文件失败:", generateError);
            this.statusText = "生成ZIP文件时出错";
            this.isDownloading = false;
          }
        } catch (error) {
          console.error("创建ZIP文件失败:", error);
          this.statusText = "创建ZIP文件时出错";

          setTimeout(() => {
            this.isDownloading = false;
          }, 3000);
        }
      } else {
        this.$message.warning("请选择一条记录");
      }
    },

    async downloadFileAsBlob(url) {
      try {
        const response = await fetch(url);
        if (!response.ok) {
          throw new Error(
            `下载文件失败: ${response.status} ${response.statusText}`
          );
        }

        const blob = await response.blob();

        // 验证blob是否有效
        if (!(blob instanceof Blob)) {
          throw new Error("返回的不是有效的Blob对象");
        }

        if (blob.size === 0) {
          throw new Error("文件内容为空");
        }

        return blob;
      } catch (error) {
        console.error("下载文件出错:", error);
        throw error;
      }
    },
    /** 翻页操作 */
    onShowSizeChange(current, pageSize) {
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSizeChange(current, size) {
      this.queryParam.pageNum = 1;
      this.queryParam.pageSize = size;
      this.getList();
    },
    /** 翻页操作 */
    changeSize(current, pageSize) {
      this.queryParam.pageNum = current;
      this.queryParam.pageSize = pageSize;
      this.getList();
    },
    /** 翻页操作 */
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys;
      this.selectedRows = selectedRows;
      this.ids = this.selectedRows.map((item) => item.id);
      this.single = selectedRowKeys.length !== 1;
      this.multiple = !selectedRowKeys.length;
    },
    /** 查询折叠和展开操作 */
    toggleAdvanced() {
      this.advanced = !this.advanced;
    },
    handleAdd() {
      this.showAddModal = true;
      this.$nextTick(() => this.$refs.bizNewsAddForm.handleAdd());
    },
    handleUpdate(record, ids) {
      this.showEditModal = true;
      this.$nextTick(() =>
        this.$refs.bizNewsEditForm.handleUpdate(record, ids)
      );
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      var that = this;
      const bizNewsIds = row.id || this.ids;
      this.$confirm({
        title: "确认删除所选中数据?",
        onOk() {
          return delBizNews(bizNewsIds).then(() => {
            that.onSelectChange([], []);
            that.getList();
            that.$message.success("删除成功", 3);
          });
        },
        onCancel() {},
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      var that = this;
      this.$confirm({
        title: "是否确认导出?",
        content: "此操作将导出当前条件下所有数据而非选中数据",
        onOk() {
          return exportBizNews(that.queryParam).then((response) => {
            that.download(response.msg);
            that.$message.success("导出成功", 3);
          });
        },
        onCancel() {},
      });
    },
  },
};
</script>
